//
//  MZDimensionCodeViewController.m
//  minzuwenhuagong
//
//  Created by WANG CUNRUI on 14-5-23.
//  Copyright (c) 2014年 WANG CUNRUI. All rights reserved.
//

#import "MZDimensionCodeViewController.h"
#import "GTMBase64.h"
#import "NSString+ThreeDES.h"


@interface MZDimensionCodeViewController()
@property UIActivityIndicatorView * loadingAlertWindow;
@end

@implementation MZDimensionCodeViewController
{
    UIImageView *alertViewBackView;
    BOOL done;
    BOOL done2;
    NSString *codeStr;
    NSString *tempStr;
    NSString *resultStr;
    ASIHTTPRequest *requestOfURL;
    NSString *resultID;
    
}
@synthesize saoYiSaoBut = _saoYiSaoBut;
@synthesize littleLable = _littleLable;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    //self.view.backgroundColor = [UIColor yellowColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    CGRect frame = self.view.bounds;
    CGSize f = frame.size;
    CGFloat h = f.height;
//    CGFloat w = f.width;
    [self.view setBackgroundColor:[UIColor colorWithRed:0.9373 green:0.9216 blue:0.9059 alpha:1.0]];
    UIImageView *moImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tempcode.png"]];
    moImage.frame = CGRectMake(60, 0.08*h, 205,0.4*h);
    [self.view addSubview:moImage];
    _littleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 0.563*h, 280, 50)];
    _littleLable.font = [UIFont boldSystemFontOfSize:13];
    _littleLable.textColor = [UIColor blackColor];
    _littleLable.text = @"可解析民族文化宫相关展品和藏品二维码";
    _littleLable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_littleLable];
    _saoYiSaoBut = [UIButton buttonWithType:UIButtonTypeCustom];
    _saoYiSaoBut.frame = CGRectMake(25, 0.51*h, 270, 40);
    _saoYiSaoBut.layer.cornerRadius = 4;
    [_saoYiSaoBut setTitle:@"二维码扫描" forState:UIControlStateNormal];
    [_saoYiSaoBut addTarget:self action:@selector(butClick:) forControlEvents:UIControlEventTouchUpInside];
    [_saoYiSaoBut setBackgroundColor:[UIColor colorWithRed:66/255.0 green:186/255.0 blue:21/255.0 alpha:1.0]];
//    [_saoYiSaoBut addTarget:self action:@selector(butClick:) forControlEvents:UIControlEventTouchUpInside];
    _saoYiSaoBut.tag = 1;
    [self.view addSubview:_saoYiSaoBut];

    
}

- (void)checkBoxBigButClick
{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"touchUIInsideSaoYiSao" object:nil];
    
}
- (void)butClick:(UIButton *)but
{
    if(_reader)
    {
        [_reader.readerView stop];
        for(UIView *subViews in _reader.view.subviews)
            [subViews removeFromSuperview];
        [_reader.view removeFromSuperview];
        _reader.view = nil;
    }
    
    _reader = [ZBarReaderViewController new];
    _reader.readerDelegate = self;
    _reader.supportedOrientationsMask = ZBarOrientationMaskAll;
    
    //自定义ZBarReaderViewController
    for (UIView *temp in [_reader.view subviews])
    {
        for (UIButton *button in [temp subviews])
        {
            if ([button isKindOfClass:[UIButton class]])
            {
                [button removeFromSuperview];
            }
        }
        
        for (UIToolbar *toolbar in [temp subviews])
        {
            if ([toolbar isKindOfClass:[UIToolbar class]])
            {
                [toolbar setHidden:YES];
                [toolbar removeFromSuperview];
            }
        }
    }
    
    //画中间的基准线
    
    UIView* line = [[UIView alloc] initWithFrame:CGRectMake(40, 220, 240, 1)];
    
    line.backgroundColor = [UIColor redColor];
    
    [_reader.view addSubview:line];
    
    
    //最上部view
    
    UIView* upView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    
    upView.alpha = 0.3;
    
    upView.backgroundColor = [UIColor blackColor];
    
    [_reader.view addSubview:upView];
    
    //用于说明的label
    
    UILabel * labIntroudction= [[UILabel alloc] init];
    
    labIntroudction.backgroundColor = [UIColor clearColor];
    
    labIntroudction.frame=CGRectMake(15, 20, 290, 50);
    
    labIntroudction.numberOfLines=2;
    
    labIntroudction.textColor=[UIColor whiteColor];
    
    labIntroudction.text=@"将二维码图像置于矩形方框内，离手机摄像头10CM左右，系统会自动识别。";
    
    [upView addSubview:labIntroudction];
    
    //左侧的view
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 80, 20, 280)];
    
    leftView.alpha = 0.3;
    
    leftView.backgroundColor = [UIColor blackColor];
    
    [_reader.view addSubview:leftView];
    
    //右侧的view
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(300, 80, 20, 280)];
    
    rightView.alpha = 0.3;
    
    rightView.backgroundColor = [UIColor blackColor];
    
    [_reader.view addSubview:rightView];
    
    
    //底部view
    
    UIView * downView = [[UIView alloc] initWithFrame:CGRectMake(0, 360, 320, 145)];
    
    downView.alpha = 0.3;
    
    downView.backgroundColor = [UIColor blackColor];
    
    [_reader.view addSubview:downView];
    
    
    //用于取消操作的button
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    cancelButton.alpha = 0.4;
    
    [cancelButton setFrame:CGRectMake(20, 390, 280, 40)];
    
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    
    [cancelButton.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
    
    [cancelButton addTarget:self action:@selector(dismissOverlayView:)forControlEvents:UIControlEventTouchUpInside];
    
    [_reader.view addSubview:cancelButton];
    
    ZBarImageScanner *scanner = _reader.scanner;
    
    
    // EXAMPLE: disable rarely used I2/5 to improve performance
    [scanner setSymbology: ZBAR_I25
                   config: ZBAR_CFG_ENABLE
                       to: 0];
    [self presentViewController:_reader animated:YES completion:nil];
}

- (void)dismissOverlayView:(id)sender{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    _loadingAlertWindow = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _loadingAlertWindow.frame = CGRectMake(120, 45, 30, 30);
    [_loadingAlertWindow startAnimating];
    [picker dismissViewControllerAnimated:YES completion:^{
        [picker removeFromParentViewController];
        
        UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
        //初始化
        ZBarReaderController * read = [ZBarReaderController new];
        //设置代理
        read.readerDelegate = self;
        CGImageRef cgImageRef = image.CGImage;
        ZBarSymbol * symbol = nil;
        id <NSFastEnumeration> results = [read scanImage:cgImageRef];
        for (symbol in results)
        {
            break;
        }
        NSString * result;
        if ([symbol.data canBeConvertedToEncoding:NSShiftJISStringEncoding])
            
        {
            result = [NSString stringWithCString:[symbol.data cStringUsingEncoding: NSShiftJISStringEncoding] encoding:NSUTF8StringEncoding];
        }
        else
        {
            result = symbol.data;
        }
        
        NSLog(@"%@",result);
        resultStr = result;
        NSLog(@"1111%@",resultStr);
        NSRange range = [resultStr rangeOfString:@"http://www.mzdigital.cn"];
        if (range.location == NSNotFound) {
            [self jiexierror];
            
        }else if([resultStr rangeOfString:@"?"].location !=NSNotFound) {
            NSArray *codeArray = [result componentsSeparatedByString:@"?"];
            codeStr = [codeArray objectAtIndex:1];
            NSString *string2 = [codeStr substringFromIndex:3];
            NSLog(@"2222%@",string2);
            resultID = [NSString decryptWithText:string2];
            NSLog(@"3333%@",resultID);
            [self jiexisuccess:(resultID)];

        }else {
            NSString *string3 = [resultStr substringFromIndex:15];
            resultID = [self ReverseStr:string3];
            [self jiexisuccess:(resultID)];
        }
        
    }];
}

//-(NSString *)ReverseStr:(NSString *)str
//{
//    
//    NSArray *arrayWord = [str componentsSeparatedByString:@""];
//    NSArray *array = [[NSArray alloc]init];
//    NSString *str1 = [[NSString alloc]init];
//    for (int i = arrayWord.count - 1, j = 0;j <= arrayWord.count - 1,i >= 0;i--,j++)
//    {
//        [array objectAtIndex:2] = [arrayWord objectAtIndex:2];
//    }
//    str1 = [array componentsJoinedByString:@""];
//    return str1;
//}

//char *strrev1(const char *str)
-(NSString *)ReverseStr:(NSString *)myString
{
    const char *str = [myString cStringUsingEncoding:[NSString defaultCStringEncoding]];
    int len = strlen(str);
    char *tmp = (char*)malloc(len + 1);
    strcpy(tmp,str);
    
    int i = 0;
    for (i = 0; i < len/2; ++i)
    {
        
        char c = tmp[i];
        
        tmp[i] = tmp[len-i-1];
        
        tmp[len-i-1] = c;
        
    }
    
    NSString *strNSString = [[NSString alloc] initWithUTF8String:tmp];
    return strNSString;
    free(tmp);
    
}



-(void)jiexierror
{
    _loadingAlertWindow.hidden = YES;
    ErrorController = [[MZErrorViewController alloc] init];
//    [ErrorController makeViewfalus];
    [self.navigationController pushViewController:ErrorController animated:YES];
;
}

-(void)jiexisuccess:(NSString *)str
{
    MZDCDetailViewController *saomaDetailVC =[[MZDCDetailViewController alloc] init];
    saomaDetailVC.wenwuID = resultID;
    NSLog(@"3333%@",resultID);
    [self.navigationController pushViewController:saomaDetailVC animated:YES];
}


- (void)requestFinished:(ASIHTTPRequest *)request
{
    if (requestOfURL == request) {

    
        NSLog(@"二维码解析成功");
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"二维码解析失败失败");
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
